package com.photo.photePro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.photo.photePro.entity.Contestant;
import com.photo.photePro.mapper.ContestantMapper;
import com.photo.photePro.service.ContestantService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 参赛选手Service实现类
 */
@Service
public class ContestantServiceImpl extends ServiceImpl<ContestantMapper, Contestant> implements ContestantService {

    /**
     * 分页查询参赛选手
     */
    @Override
    public Page<Contestant> pageQuery(int page, int pageSize, String realName, Integer status) {
        Page<Contestant> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Contestant> queryWrapper = new LambdaQueryWrapper<>();
        
        // 按姓名模糊查询
        if (StringUtils.hasLength(realName)) {
            queryWrapper.like(Contestant::getRealName, realName);
        }
        
        // 按状态筛选
        if (status != null) {
            queryWrapper.eq(Contestant::getStatus, status);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Contestant::getCreateTime);
        
        return this.page(pageInfo, queryWrapper);
    }
    
    /**
     * 根据用户ID查询参赛选手
     */
    @Override
    public Contestant getByUserId(Long userId) {
        LambdaQueryWrapper<Contestant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Contestant::getUserId, userId);
        return this.getOne(queryWrapper);
    }
    
    /**
     * 审核参赛选手
     */
    @Override
    public boolean audit(Long id, Integer status, String rejectReason) {
        Contestant contestant = this.getById(id);
        if (contestant == null) {
            return false;
        }
        
        contestant.setStatus(status);
        if (status == 2 && StringUtils.hasLength(rejectReason)) {
            contestant.setRejectReason(rejectReason);
        }
        contestant.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(contestant);
    }
    
    /**
     * 检查身份证号或手机号是否已经报名
     */
    @Override
    public boolean checkExistsByIdCardOrPhone(String idCard, String phone) {
        LambdaQueryWrapper<Contestant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Contestant::getIdCard, idCard)
                    .or()
                    .eq(Contestant::getPhone, phone);
        
        return this.count(queryWrapper) > 0;
    }
} 